package com.xbn.netty.coder2;

import com.xbn.netty.codec.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author XBN
 * @date 2020/10/19 14:30
 * @email 78742541@qq.com
 */
public class NettyClientHandler  extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
           //随机发送Student或者Worker对象
        int random = new Random().nextInt(3);
        MyStudent.MyMessage myMessage=null;
        //如果是0就发送一个Student对象
        if(0==random)
        {
            myMessage = MyStudent.MyMessage.newBuilder().setDataType(MyStudent.MyMessage.DataType.StudentType)
                    .setStudent(MyStudent.Student.newBuilder().setId(5).setName("学生").build()).build();
            System.out.println("发送的数据是学生类型");
        }
        else {
            //发送一个worker对象
            myMessage = MyStudent.MyMessage.newBuilder().setDataType(MyStudent.MyMessage.DataType.WorkerType)
                    .setWorker(MyStudent.Worker.newBuilder().setAge(25).setName("职员").build()).build();
            System.out.println("发送的数据是职员类型");
        }
        ctx.writeAndFlush(myMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf= (ByteBuf) msg;
        System.out.println("服务器回复的消息:"+buf
        .toString(CharsetUtil.UTF_8));
        System.out.println("服务器端的地址:"+ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {


        cause.printStackTrace();
        ctx.close();
    }
}
